<?php
require 'db.php'; // 包含数据库连接

// 检查是否提供了文章ID
if (!isset($_GET['id'])) {
    echo json_encode(['error' => '文章ID未提供']);
    exit();
}

$article_id = $_GET['id'];

// 获取指定ID的文章
$stmt = $conn->prepare("SELECT title, content, author_name, created_at FROM articles WHERE id = ? AND status = 'approved'");
$stmt->bind_param("i", $article_id);
$stmt->execute();
$stmt->bind_result($title, $content, $author, $created_at);
$stmt->fetch();
$stmt->close();

if ($title) {
    // 获取评论信息
    $stmt = $conn->prepare("SELECT comment, created_at, id, commenter_id FROM comments WHERE article_id = ?");
    $stmt->bind_param("i", $article_id);
    $stmt->execute();
    $stmt->bind_result($comment, $comment_created_at, $comment_id, $commenter_id);

    $comments = [];
    $commenter_ids = [];
    while ($stmt->fetch()) {
        $comments[] = [
            'comment' => nl2br(htmlspecialchars($comment)),
            'created_at' => $comment_created_at,
            'comment_id' => $comment_id,
            'commenter_id' => $commenter_id
        ];
        $commenter_ids[] = $commenter_id;
    }
    $stmt->close();

    if (count($commenter_ids) > 0) {
        // 去重
        $commenter_ids = array_unique($commenter_ids);

        // 将所有评论者ID用逗号分隔
        $placeholders = implode(',', array_fill(0, count($commenter_ids), '?'));

        // 动态生成类型字符串
        $types = str_repeat('i', count($commenter_ids));

        $sql = "SELECT id, username FROM users WHERE id IN ($placeholders)";
        $stmt = $conn->prepare($sql);

        // 动态绑定参数
        $stmt->bind_param($types, ...$commenter_ids);
        $stmt->execute();
        $stmt->bind_result($user_id, $username);

        $users = [];
        while ($stmt->fetch()) {
            $users[$user_id] = $username;
        }
        $stmt->close();

        // 将用户名添加到评论中
        foreach ($comments as &$comment) {
            $comment['commenter'] = $users[$comment['commenter_id']];
        }
    }

    // 返回JSON格式的文章详情和评论
    header('Content-Type: application/json');
    echo json_encode([
        'title' => $title,
        'content' => nl2br(htmlspecialchars($content)),
        'author' => $author,
        'created_at' => $created_at,
        'comments' => $comments
    ]);
} else {
    echo json_encode(['error' => '未找到文章']);
}

$conn->close();
?>
